package cn.nubia.admin.sysconfig.service;

import cn.nubia.admin.common.mybatis.bean.Paged;
import cn.nubia.admin.common.mybatis.bean.Query;
import cn.nubia.admin.common.mybatis.service.BaseServiceImpl;
import cn.nubia.admin.sysconfig.bean.*;
import cn.nubia.admin.sysconfig.query.UserQuery;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 用户管理操作层.
 */
@Service
public class UserService extends BaseServiceImpl<User> {


    @Autowired
    private RoleUserService roleUserService;

    @Autowired
    private RoleResourceService roleResourceService;

    @Autowired
    private MenuResourceService menuResourceService;

    @Autowired
    private UserResourceService userResourceService;
    @Autowired
    SystemLogService systemLogService;
    /**
     * 用户列表功能.
     *
     * @param userQuery 用户查询条件
     * @return 分页对象
     */
    public Paged<User> findPage(UserQuery userQuery) {
        Query<User> query = Query.build(User.class);
        if (userQuery.getName() != null && userQuery.getName() != "") {
            query.addLike("name", userQuery.getName());
        }
        if (userQuery.getUsername() != null && userQuery.getUsername() != "") {
            query.addLike("username", userQuery.getUsername());
        }
        query.addEq("type", userQuery.getType());
        query.addEq("enable", userQuery.getEnable());
        query.setPaged(userQuery.getPageNo(), userQuery.getPageSize());
        return findPagedByQuery(query);
    }


    public void save(User user) {

        String cryptedPwd = new Md5Hash(user.getPassword()).toString();
        user.setPassword(cryptedPwd);
        if (null == user.getId()) {
            user.setCreateTime(new Date());
            insert(user);
            systemLogService.log(SystemLog.ModuleTypeEnum.USERLIST, SystemLog.OperateTypeEnum.ADD, user.getId());

        } else {
            user.setUpdateTime(new Date());
            update(user);
            systemLogService.log(SystemLog.ModuleTypeEnum.USERLIST, SystemLog.OperateTypeEnum.EDIT, user.getId());

        }
    }


    /**
     * 获取用户权限.
     *
     * @param userId
     * @return
     */
    public Set<MenuResource> findPermission(Integer userId) {
        User user = get(userId);
        List<MenuResource> resources;
        //获取用户角色权限
        if (user.getType() == 1) {
            resources = menuResourceService.findAll();
        } else {
            Role userRole = roleUserService.getRoleByUserId(userId);
            if (null == userRole || userRole.getEnable() != 0) {
                return null;
            }
            resources = roleResourceService.findByRoleId(userRole.getId());
        }
        //获取用户权限
        List<MenuResource> userMenuResource = new ArrayList<>();
        UserResource userResource = userResourceService.get(userId);
        if (null != userResource && null != userResource.getResourceIds()) {
            String[] userResourceIds = userResource.getResourceIds().split(",");
            List<MenuResource> allResources = menuResourceService.findAll();
            for (MenuResource menuResource : allResources) {
                for (String resourceId : userResourceIds) {
                    if (resourceId != null && !"".equals(resourceId)) {
                        if (menuResource.getId().equals(Integer.valueOf(resourceId))) {
                            userMenuResource.add(menuResource);
                        }
                    }

                }
            }
        }

        //合并权限
        Set<MenuResource> permissionList = new HashSet<MenuResource>();

        for (MenuResource resource : resources) {
            if (resource.getEnable() == 0) {
                permissionList.add(resource);
            }
        }
        for (MenuResource resource : userMenuResource) {
            if (resource.getEnable() == 0) {
                permissionList.add(resource);
            }
        }

        return permissionList;
    }

    public User getActiveUser(String userName) {

        Query<User> query = Query.build(User.class);
        query.addEq("username", userName);
        query.addEq("enable", User.ENABLE);
        return get(query);
    }
}
